import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { gettoken } from '@/request/api/api.ts'
let huoqutoken = async () => {
   let data: any = await gettoken()
   return data
}


// 创建axios实例
const instance = axios.create({
   baseURL: '/api', // 设置API的基础URL
});

// 请求拦截器
instance.interceptors.request.use(
   (config: AxiosRequestConfig): any => {
      // 可在请求发送前对config进行修改，如添加请求头等
      const headers = config.headers || {};
      let access_token = localStorage.getItem('access_token');
      let REFRESH_token = localStorage.getItem('REFRESH_token');
      headers['Authorization'] = `short+${access_token} length+${REFRESH_token}`;
      config.headers = headers;
      return config;
   },
   (error: AxiosError) => {
      // 处理请求错误
      return Promise.reject(error);
   }
);

// 响应拦截器
instance.interceptors.response.use(
   (response: AxiosResponse) => {
      // console.log(response);
      if (response.data.code === 1001) {
         alert('没有携带token，请检查')
      } else if (response.data.code === 1002) {
         // alert('短token过期，请重新获取')
         huoqutoken()
      } else if (response.data.code === 1003) {
         // alert('没有携带长token')
      } else if (response.data.code === 1004) {
         alert('长token过期，请重新登录')
         // 路由跳转
         window.location.href = '/'
      } else if (response.data.code === 2000) {
         localStorage.setItem('access_token', response.data.access_token)
      }
      return response;
   },
   (error: AxiosError) => {
      // 处理响应错误
      return Promise.reject(error);

   }
);


export default instance
